<template>
	<view class="pages-technician">
		<fixed>
			<view class="fix-info choose fill-body rel">
				<view class="space-top abs" :style="{background:primaryColor}"></view>
				<view class="search-info fill-base pt-lg pl-lg pr-lg pb-md abs">
					<view class="flex-center pb-md">
						<!-- <view class="city-info">
							<picker @change="pickerChange($event)" :value="cityIndex" :range="cityList"
								range-key="title">
								<view class="city-info flex-y-center font32" style="color: red;">
									<view>
										<block v-if="cityList&&cityList.length > 0">
											{{cityIndex === -1 ? '未知' : cityList[cityIndex].title.length > 3 ? cityList[cityIndex].title.substring(0,3) + '...':cityList[cityIndex].title}}
										</block>
										<block v-else>请选择</block>
									</view>
									<i class="iconfont iconshaixuanxia-1 ml-sm"></i>
								</view>
							</picker>
						</view> -->
						<view class="font32" style="flex: 1;display: flex;align-items: center;" @click="show = true">
							<view style="margin-right: 32rpx;">点击选择日期:</view>
							<view class="" style="color: red;" @click="show = true">
								{{$u.timeFormat(value1, 'yyyy-mm-dd')}}
							</view>
							<!-- 	<search @input="toSearch" type="input" :keyword="param.coach_name" :padding="0" :radius="30"
								backgroundColor="#F0F0F0" placeholder="请输入房间名称">
							</search> -->

						</view>
						<!-- <view class="" style="color: red;" @click="show = true">
							点击选择日期
						</view> -->
					</view>
				</view>
			</view>
		</fixed>

		<view class="ml-md mr-md" :class="[{'flex-warp':configInfo.coach_list_format===2}]"
			v-if="list && list.length>0">
			<view
				:class="[{'mt-md':(configInfo.coach_list_format===1&&index!=0) || configInfo.coach_list_format===2},{'mr-md':configInfo.coach_list_format===2 && index%2==0}]"
				v-for="(item,index) in list" :key="index">
				<view class="fontw" style="font-size: 36rpx;padding: 8rpx 0;">
					{{item.store.title}}
				</view>
				<view class="" v-for="(items,indexs) in item.store.house" :key="indexs" style="margin-bottom: 16rpx;">
					<view class="" style="padding: 24rpx; background-color: #fff;border-radius: 16rpx;">
						<view class=""
							style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 24rpx;">
							<view class="font36">
								房间名称:{{items.title}}
							</view>
							<view class="" style="width: 260rpx;">
								<u-radio-group v-model="items.value" iconPlacement="left">
									<u-radio :disabled="itemz.disabled" :label="itemz.name" :name="itemz.name"
										v-for="(itemz,indexz) in items.time" :key="indexz"
										@change="groupChange(index,indexs,indexz)"></u-radio>
								</u-radio-group>
							</view>
						</view>
						<view class=""
							style="min-width: 120rpx;height: 80rpx;background: linear-gradient(68deg, #1eb481, #9ade97);padding: 0 10rpx;border-radius: 10rpx;text-align: center;line-height: 80rpx;color: #fff;"
							@click="toOrder(index,indexs,items.title)">
							预约
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- #ifdef H5 -->
		<!-- <load-more :noMore="list.current_page>=list.last_page&&list.length>0" :loading="loading" v-if="loading"> -->
		</load-more>
		<!-- <abnor v-if="!loading&&list.length<=0&&list.current_page==1"></abnor> -->
		<!-- #endif -->
		<!-- #ifndef H5 -->
		<!-- <load-more :noMore="list.current_page>=list.last_page&&list.length>0&&location.lng" :loading="loading"
			v-if="loading">
		</load-more> -->
		<!-- <abnor v-if="!loading&&list.length<=0&&list.current_page==1&&location.address"></abnor> -->
		<abnor @confirm="toOpenLocation" :tip="[{ text: '定位失败，请开启地理位置授权后刷新页面重试~', color: 0 }]"
			:button="[{ text: '开启定位' , type: 'confirm' }]" btnSize="" v-if="!loading && !location.address"> </abnor>
		<!-- #endif -->

		<technician-list-popup ref="technician_list_popup"></technician-list-popup>

		<!-- <uni-popup ref="choose_city_item" type="top" :custom="true" :zIndex="999">
			<view :style="{height:configInfo.navBarHeight + 8 + 'px'}"></view>
			<view class="choose-city-popup rel">
				<image class="city-img" src="https://lbqny.migugu.com/admin/anmo/technician/no_city.png"></image>
				<view class="text f-paragraph c-base abs">
					很抱歉,该城市未开通, 点击左上角切换其他城市下单服务
				</view>
				<view class="flex-between">
					<view></view>
					<view @tap.stop="$refs.choose_city_item.close()"
						class="item-btn flex-center f-paragraph c-title text-bold radius">知道了</view>
				</view>
			</view>
		</uni-popup> -->

		<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel="show = false"
			@confirm="confirm"></u-datetime-picker>
		<view class="space-max-footer"></view>
		<!-- <fix-bottom-button @confirm="toBack" :text="[{type:'confirm',text:pageLen>1?`返回上页`:`返回首页`}]" bgColor="#fff">
		</fix-bottom-button> -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import technicianListItem from "@/components/technician-list-item.vue"
	import technicianListPopup from "@/components/technician-list-popup.vue"
	export default {
		components: {
			technicianListItem,
			technicianListPopup
		},
		data() {
			return {
				isLoad: false,
				options: {},
				param: {
					page: 1,
					ser_id: 0,
					coach_name: ''
				},
				list: [],
				loading: true,
				lockTap: false,
				pageLen: 1,
				valueName: '',
				show: false,
				value1: Number(new Date()),
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			cityId: state => state.technician.cityId,
			cityIndex: state => state.technician.cityIndex,
			cityList: state => state.technician.cityList,
			loginType: state => state.user.loginType,
			userInfo: state => state.user.userInfo,
			location: state => state.user.location,
		}),
		async onLoad(options) {
			this.options = options
			// #ifndef H5
			this.$util.showLoading()
			// #endif
			await this.initIndex()
			this.isLoad = true
		},
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			this.initRefresh();
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			this.getList();
		},
		methods: {
			...mapActions(['getCityList']),
			...mapMutations(['updateUserItem', 'updateTechnicianItem']),
			async initIndex(refresh = false) {
				// #ifdef H5
				if (!refresh && this.$jweixin.isWechat()) {
					await this.$jweixin.initJssdk();
					this.$jweixin.wxReady(() => {
						this.$jweixin.hideOptionMenu()
					})
				}
				// #endif
				this.pageLen = getCurrentPages().length
				this.getList(this.cityList.length == 0)
			},
			initRefresh() {
				this.param.page = 1
				this.initIndex(true)
			},
			pickerChange(e, val) {
				let ind = e.target.value
				this.updateTechnicianItem({
					key: 'cityIndex',
					val: ind
				})
				this.updateTechnicianItem({
					key: 'cityId',
					val: this.cityList[ind].id
				})
				this.param.page = 1
				this.getList()
			},
			groupChange(index, indexs, indexz) {
				this.list.map(item => {
					item.store.house.map(items => {
						items.value = ''
						this.valueName = ''
					})
				})
				console.log(this.list);
				this.valueName = this.list[index].store.house[indexs].time[indexz].name
				this.list[index].store.house[indexs].value = this.list[index].store.house[indexs].time[indexz].name
				// if (this.this.list[index].store.house[indexs].time[indexz].disabled) {
				// 	uni.showToast({
				// 		icon: "error",
				// 		title: '该时间段已预被约',
				// 		duration: 1000
				// 	})
				// } else {
				// 	this.valueName = this.this.list[index].store.house[indexs].time[indexz].name
				// }
			},
			confirm() {
				this.show = false
				this.getList(true, 1)
			},
			getTodayDate() {
				const today = new Date();
				const year = today.getFullYear();
				const month = today.getMonth() + 1; // 月份是从0开始的
				const day = today.getDate();

				// 格式化月份和日期，保持两位数
				const formattedMonth = month < 10 ? '0' + month : month;
				const formattedDay = day < 10 ? '0' + day : day;

				return `${year}-${formattedMonth}-${formattedDay}`;
			},
			toOpenLocation() {
				this.$util.checkAuth({
					type: 'userLocation'
				})
				// #ifdef APP-PLUS
				uni.getSystemInfo({
					success: (sys) => {
						if (sys.platform == 'ios') {
							plus.runtime.openURL("app-settings://");
						} else {
							var main = plus.android.runtimeMainActivity();
							var Intent = plus.android.importClass(
								"android.content.Intent");
							//可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS  
							var mIntent = new Intent(
								'android.settings.LOCATION_SOURCE_SETTINGS'
							);
							main.startActivity(mIntent);
						}
					}
				})
				// #endif
			},
			toSearch(val) {
				this.param.page = 1
				this.param.coach_name = val
				this.getList()
			},
			// 选择地区
			async toChooseLocation(e) {
				await this.$util.checkAuth({
					type: 'userLocation'
				})

				let {
					lat: locaLat = '',
					lng: locaLng = ''
				} = this.location

				let param = {}
				if (!locaLat && !locaLng) {
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						await this.$jweixin.wxReady2();
						let {
							latitude,
							longitude
						} = await this.$jweixin.getWxLocation()
						locaLat = latitude
						locaLng = longitude
					}
					// #endif
					// #ifdef APP-PLUS
					let location = await this.$util.getBmapLocation()
					locaLat = location.lat
					locaLng = location.lng
					// #endif
				}

				// #ifndef MP-WEIXIN
				param = {
					latitude: locaLat,
					longitude: locaLng
				}
				// #endif
				let [, {
					address = '',
					longitude: lng,
					latitude: lat,
					province = '',
					city = '',
					district = '',
				}] = await uni.chooseLocation(param);
				if (!lng) return
				let location = {
					lng,
					lat,
					address,
					province,
					city,
					district
				}
				this.updateUserItem({
					key: 'location',
					val: location
				})
				this.param.page = 1
				await this.getList(true, 1)
			},
			async getList(refresh = false, change = 0) {
				let {
					location
				} = this
				if (!location.lat || (location.lat && location.address == '定位失败')) {
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						// await this.$jweixin.initJssdk();
						await this.$jweixin.wxReady2();
						let {
							lat = '', lng = ''
						} = location
						if (!lat && !lng) {
							let {
								latitude,
								longitude
							} = await this.$jweixin.getWxLocation()
							lat = latitude
							lng = longitude
							location = {
								lng,
								lat,
								address: '定位失败',
								province: '',
								city: '',
								district: ''
							}
						}
						if (lat && lng) {
							let key = `${lat},${lng}`
							let data = await this.$api.base.getMapInfo({
								location: key
							})
							let {
								status,
								result
							} = JSON.parse(data)
							if (status == 0) {
								let {
									address,
									address_component
								} = result
								let {
									province,
									city,
									district
								} = address_component
								location = {
									lng,
									lat,
									address,
									province,
									city,
									district
								}
							}
						}
					}
					// #endif
					// #ifndef H5
					location = await this.$util.getBmapLocation()
					// #endif

					this.updateUserItem({
						key: 'location',
						val: location
					})
				}

				let {
					lng = 0,
						lat = 0
				} = location
				if (refresh) {
					await this.getCityList({
						lng,
						lat,
						change
					})
				}

				let {
					id: ser_id,
					store_id = 0
				} = this.options
				let {
					list: oldList,
					param,
					cityList,
					cityIndex,
					cityId: city_id
				} = this

				let ind = cityList.findIndex(item => {
					return item.id == city_id
				})

				// if (ind == -1) {
				// 	this.$refs.choose_city_item.open()
				// 	this.loading = false
				// 	this.$util.hideAll()
				// 	this.list = {
				// 		data: [],
				// 		last_page: 1,
				// 		current_page: 1
				// 	}
				// 	return
				// }

				// city_id = ind == -1 ? 0 : city_id
				// cityIndex = ind == -1 ? 0 : ind


				// this.updateTechnicianItem({
				// 	key: 'cityIndex',
				// 	val: cityIndex
				// })

				// this.updateTechnicianItem({
				// 	key: 'cityId',
				// 	val: city_id
				// })

				param = Object.assign({}, param, {
					ser_id,
					store_id,
					// lng,
					// lat,
					// city_id,
					date: uni.$u.timeFormat(this.value1, 'yyyy-mm-dd')
				})

				let {
					coach_format = 1
				} = this.configInfo

				let methodModel = coach_format == 1 ? 'serviceCoachList' : 'typeServiceCoachList'
				let newList = await this.$api.service.dietHouse(param);
				var date1 = new Date(uni.$u.timeFormat(this.value1, 'yyyy-mm-dd')).getTime();
				var date2 = new Date(this.getTodayDate()).getTime();
				newList.map(item => {
					item.store.house.map(items => {
						items.value = ''
						items.time = [{
							name: '午餐',
							disabled: false
						}, {
							name: '晚餐',
							disabled: false
						}]

						if (items.is_lunch == 0) {
							if (date1 <= date2) {
								if (this.distime() < 9) {
									items.time[0].disabled = false
								} else {
									items.time[0].disabled = true
								}
							} else {
								items.time[0].disabled = false
							}
						} else {
							items.time[0].disabled = true
						}
						if (items.is_dinner == 0) {
							if (date1 <= date2) {
								if (this.distime() < 14) {
									items.time[1].disabled = false
								} else {
									items.time[1].disabled = true
								}
							} else {
								items.time[1].disabled = false

							}
						} else {
							items.time[1].disabled = true
						}
					})
				})
				console.log(newList, 'newList');
				if (this.param.page == 1) {
					this.list = newList
				} else {
					newList.data = oldList.data.concat(newList.data)
					this.list = newList
				}
				console.log(this.list, 'this.list');
				this.loading = false
				this.$util.hideAll()
			},
			async toShowPopup(index, indexs, key) {
				this.$refs.technician_list_popup.toShowPopup(this.list[index].store.coach[indexs], key)
			},
			async toCollect(index, indexs) {
				let {
					id,
					is_collect,
					collect_num
				} = this.list[index].store.house[indexs]
				let methodModel = is_collect ? 'delCollect' : 'addCollect'
				await this.$api.mine[methodModel]({
					coach_id: id
				})
				this.$util.showToast({
					title: is_collect ? '取消成功' : '收藏成功'
				})
				this.list[index].store.coach[indexs].is_collect = is_collect == 1 ? 0 : 1
				this.list[index].store.coach[indexs].collect_num = is_collect == 1 ? collect_num - 1 : collect_num + 1
			},
			// 技-师详情
			goInfo(index) {
				let {
					id,
					store = {}
				} = this.list[index].store.house[indexs]
				let {
					plugAuth = {}
				} = this.configInfo
				this.$util.goUrl({
					url: plugAuth.store && store && store.id ? `/shopstore/pages/detail?id=${store.id}` :
						`/user/pages/technician-info?id=${id}`
				})
			},
			// 预约
			async toOrder(index, indexs, tit) {
				if (this.list[index].store.house[indexs].value == '') {
					uni.showToast({
						icon: 'error',
						title: '请选择时间段',
						duration: 1000
					})
					return
				}
				let {
					id: house_id
				} = this.list[index].store.house[indexs]
				let {
					id: service_id
				} = this.options
				let ltime = ''
				if (this.list[index].store.house[indexs].value == '午餐') {
					ltime = '12:00'
				}
				if (this.list[index].store.house[indexs].value == '晚餐') {
					ltime = '17:00'
				}
				let time = this.$u.timeFormat(this.value1, 'yyyy-mm-dd')
				if (this.lockTap) return;
				this.lockTap = true;
				try {
					await this.$api.order.addCar({
						service_id,
						house_id,
						num: 1,
						is_top: 1,
						coach_service: 1
					})
					this.lockTap = false
					let url =
						`/user/pages/order?house_id=${house_id}&ser_id=${service_id}&type=${this.valueName}&time=${time}&vName=${tit}`
					this.$util.goUrl({
						url
					})
				} catch (e) {
					this.lockTap = false
				}
			},
			toBack() {
				let {
					pageLen
				} = this
				let url = pageLen > 1 ? 1 : `/pages/service`
				let openType = pageLen > 1 ? `navigateBack` : `reLaunch`
				this.$util.goUrl({
					url,
					openType
				})
			},
			distime() {
				var now = new Date();
				var hours = now.getHours(); // 获取当前小时数
				return hours
			}
		}
	}
</script>


<style lang="scss">
	.pages-technician {}

	.u-radio-group {
		justify-content: space-between;
	}
</style>